<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import {
  getDevicesApi,
  addDeviceApi,
  deleteDeviceApi,
  updateDeviceApi,
  downloadDeviceTemplateApi,
  getDeviceStatusApi
} from '@/api/role'
import type { DepartmentItem } from '@/api/department/types'
import { getUserListApi, getTreeDepartmentsApi } from '@/api/department'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { ElTag, ElUpload, ElIcon, ElMessage } from 'element-plus'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import Write from './components/AssetManageWrite.vue'
import Detail from './components/AssetManageDetail.vue'
import { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'
import * as XLSX from 'xlsx'
import { Plus } from '@element-plus/icons-vue'
const PATH_URL = import.meta.env.VITE_API_BASE_PATH
import { useUserStoreWithOut } from '@/store/modules/user'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useButtonPermiss } from '@/utils/buttonpermiss'
const haspermiss = ref<String[]>([])
const getUseButtonPermiss = () => {
  useButtonPermiss().then((res) => {
    haspermiss.value = res
  })
}
getUseButtonPermiss()
const userStore = useUserStoreWithOut()
const uploadUrl = PATH_URL + 'api/Device/ExportDevices'
const headers = ref({ Authorization: userStore.getToken ?? '' })
// console.log('uploadUrl', uploadUrl)
interface deviceInfo {
  deviceNo: string
  deviceName: string
  deviceType: string
  depNo: string
  depName: string
  userNo: string
  userName: string
  stationNo: string
  stationName: string
  deviceStatus: string
  interNo: string
  manufacturer: string
  createTime: string
  remark: string
}
interface deviceInfoExport {
  国际编号: string
  设备编号: string
  设备名称: string
  设备厂商: string
  设备型号: string
  设备状态: string
  部门编号: string
  部门名称: string
  采集站编号: string
  采集站名称: string
  用户编号: string
  用户名称: string
  备注: string
  创建时间: string
}
const { t } = useI18n()
const ids = ref<string[]>([])
let list: deviceInfo[] = []
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getDevicesApi({
      pageNo: unref(currentPage),
      pageRow: unref(pageSize),
      pageModel: { ...unref(searchParams) }
    })
    console.log('depGuid: userStore.userInfo.depGuid', userStore.userInfo.depGuid)
    list = res.data.pageModels || []
    return {
      list: list,
      total: res.data.totalCount
    }
  },
  fetchDelApi: async () => {
    const res = await deleteDeviceApi(unref(ids))
    return !!res
  }
})

const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods
const delLoading = ref(false)
const delData = async (row) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.guid] : elTableExpose?.getSelectionRows().map((v) => v.guid) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
interface labelSelect {
  label: string
  value: string
}
const departmentList = ref<DepartmentItem[]>([])
const deviceStatusList = ref<labelSelect[]>([])
const usersList = ref<labelSelect[]>([])
const fetchDepartment = async () => {
  const res = await getTreeDepartmentsApi({})
  departmentList.value = res.data
  const r = await getDeviceStatusApi()
  let devList: labelSelect[] = []
  r.data?.map((item) => {
    devList.push({
      label: item.configName,
      value: item.configName
    })
  })
  deviceStatusList.value = devList
  const dt = await getUserListApi({ pageFlag: false })
  let uList: labelSelect[] = []
  dt.data.pageModels?.map((item) => {
    uList.push({
      label: item.userNo + '  ' + item.userName,
      value: item.guid
    })
  })
  usersList.value = uList
}
fetchDepartment()
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'index',
    label: t('userDemo.index'),
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'index'
    }
  },

  {
    field: 'deviceNo',
    label: t('device.deviceNo')
  },
  {
    field: 'deviceName',
    label: t('device.deviceName')
  },
  {
    field: 'deviceType',
    label: t('device.deviceType')
  },
  {
    field: 'manufacturer',
    label: t('device.manufacturer')
  },

  {
    field: 'deviceStatus',
    label: t('menu.status'),
    form: {
      component: 'Select',
      value: '正常',
      componentProps: {
        placeholder: '请选择状态'
      },
      optionApi: async () => {
        return deviceStatusList.value
      }
    },
    search: {
      hidden: true
      // component: 'Select',
      // componentProps: {
      //   placeholder: '请选择状态'
      // },
      // optionApi: async () => {
      //   return deviceStatusList.value
      // }
    }
  },
  // {
  //   field: 'stationNoOrName',
  //   label: '采集站编号或名称',
  //   table: {
  //     hidden: true
  //   },
  //   form: { hidden: true },
  //   detail: {
  //     hidden: true
  //   }
  // },
  {
    field: 'stationNo',
    label: t('device.stationNo'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'stationName',
    label: t('device.stationName'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'depNo',
    label: t('userDemo.depNo'),
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'depGuid',
    label: t('userDemo.department'),
    slots: {
      default: (data) => {
        return <>{data.row.depName}</>
      }
    },
    search: {
      hidden: false,
      component: 'TreeSelect',
      componentProps: {
        nodeKey: 'guid',
        props: {
          label: 'depName',
          value: 'guid',
          children: 'children'
        },
        placeholder: '请选择部门',
        highlightCurrent: true,
        expandOnClickNode: false,
        checkStrictly: true,
        checkOnClickNode: true,
        clearable: true
      },
      optionApi: async () => {
        return departmentList.value || []
      }
    },
    form: {
      hidden: true
      // component: 'TreeSelect',
      // componentProps: {
      //   nodeKey: 'guid',
      //   props: {
      //     label: 'depName',
      //     value: 'guid',
      //     children: 'children'
      //   },
      //   placeholder: '请选择部门',
      //   highlightCurrent: true,
      //   expandOnClickNode: false,
      //   checkStrictly: true,
      //   checkOnClickNode: true,
      //   clearable: true
      // },
      // optionApi: async () => {
      //   return departmentList.value || []
      // }
    },
    table: {
      hidden: false
    },
    detail: {
      slots: {
        default: (data) => {
          return <>{data.depName || '-'}</>
        }
      }
    }
  },
  {
    field: 'userGuid',
    label: t('userDemo.userNo'),
    form: {
      component: 'Select',
      componentProps: {
        placeholder: '请选择用户',
        filterable: true
      },
      optionApi: async () => {
        return usersList.value
      }
    },
    table: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'userNo',
    label: t('userDemo.userNo'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'userName',
    label: t('userDemo.username'),
    form: {
      hidden: true
    },
    search: {
      hidden: true
      // component: 'Select',
      // componentProps: {
      //   placeholder: '请选择状态'
      // },
      // optionApi: async () => {
      //   return deviceStatusList.value
      // }
    }
  },
  {
    field: 'interNo',
    label: t('device.interNo')
  },
  {
    field: 'remark',
    label: t('common.remark'),
    form: {
      component: 'Input'
    },
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'createTime',
    label: t('userDemo.createTime'),
    width: 200,
    form: {
      hidden: true
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'date',
    label: t('problem.time'),
    search: {
      component: 'DatePicker',
      componentProps: {
        style: { width: '340px' },
        type: 'datetimerange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        StartPlaceholder: 'Start date',
        EndPlaceholder: 'End date'
      }
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    align: 'center',
    fixed: 'right',
    width: 300,
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 240,
      slots: {
        default: (data: any) => {
          const row = data.row
          return (
            <>
              {haspermiss.value.includes('编辑') ? (
                <BaseButton type="primary" onClick={() => action(row, 'edit')}>
                  {t('exampleDemo.edit')}
                </BaseButton>
              ) : null}

              <BaseButton type="success" onClick={() => action(row, 'detail')}>
                {t('exampleDemo.detail')}
              </BaseButton>
              {haspermiss.value.includes('删除') ? (
                <BaseButton type="danger" onClick={() => delData(data.row)}>
                  {t('exampleDemo.del')}
                </BaseButton>
              ) : null}
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

// const tableColumns = reactive<TableColumn[]>([
//   {
//     field: 'selection',
//     type: 'selection'
//   },
//   {
//     field: 'index',
//     label: t('userDemo.index'),
//     type: 'index'
//   },

//   {
//     field: 'depNo',
//     label: t('device.depNo')
//   },
//   {
//     field: 'depName',
//     label: t('device.depName')
//   },
//   {
//     field: 'userNo',
//     label: t('device.userNo')
//   },
//   {
//     field: 'userName',
//     label: t('device.userName')
//   },
//   {
//     field: 'deviceNo',
//     label: t('device.deviceNo')
//   },
//   {
//     field: 'deviceName',
//     label: t('device.deviceName')
//   },
//   {
//     field: 'deviceType',
//     label: t('device.deviceType')
//   },
//   {
//     field: 'deviceStatus',
//     label: t('device.deviceStatus')
//   },
//   {
//     field: 'stationNo',
//     label: t('device.stationNo')
//   },
//   {
//     field: 'stationName',
//     label: t('device.stationName')
//   },
//   {
//     field: 'createTime',
//     label: t('tableDemo.displayTime'),
//     width: 200
//   },

//   {
//     field: 'action',
//     label: t('userDemo.action'),
//     width: 240,
//     slots: {
//       default: (data: any) => {
//         const row = data.row
//         return (
//           <>
//             <BaseButton type="primary" onClick={() => action(row, 'edit')}>
//               {t('exampleDemo.edit')}
//             </BaseButton>
//             <BaseButton type="success" onClick={() => action(row, 'detail')}>
//               {t('exampleDemo.detail')}
//             </BaseButton>
//             <BaseButton type="danger" onClick={() => delData(data.row)}>
//               {t('exampleDemo.del')}
//             </BaseButton>
//           </>
//         )
//       }
//     }
//   }
// ])

// const searchSchema = reactive<FormSchema[]>([
//   {
//     field: 'depGuid',
//     label: t('userDemo.department'),
//     component: 'TreeSelect',
//     componentProps: {
//       nodeKey: 'guid',
//       props: {
//         label: 'depName',
//         value: 'guid',
//         children: 'children'
//       },
//       placeholder: '请选择部门',
//       highlightCurrent: true,
//       expandOnClickNode: false,
//       checkStrictly: true,
//       checkOnClickNode: true,
//       clearable: true
//     },
//     optionApi: async () => {
//       return departmentList.value || []
//     }
//   },
//   {
//     field: 'userNoOrName',
//     label: '',
//     component: 'Input',
//     componentProps: {
//       placeholder: '请输入用户编号或名称'
//     }
//   },
//   {
//     field: 'deviceNo',
//     label: t('device.deviceNo'),
//     component: 'Input'
//   },
//   {
//     field: 'deviceName',
//     label: t('device.deviceName'),
//     component: 'Input'
//   }
// ])

const searchParams = ref({ depGuid: userStore.userInfo.depGuid })
const setSearchParams = (params: any) => {
  if (params.date) {
    params.startTime = params.date[0]
    params.endTime = params.date[1]
    delete params.date
  }
  searchParams.value = params
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref()
const actionType = ref('')

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const action = (row: any, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = ''
}

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    let res

    if (actionType.value == 'edit') {
      formData.guid = currentRow.value.guid
      res = await updateDeviceApi(formData).finally(() => {
        saveLoading.value = false
      })
    } else {
      res = await addDeviceApi(formData).finally(() => {
        saveLoading.value = false
      })
    }
    if (res) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}
const showExport = ref(false)
const handleData = () => {
  let arr: deviceInfoExport[] = []
  list.map((item) => {
    arr.push({
      设备编号: item.deviceNo,
      设备名称: item.deviceName,
      设备型号: item.deviceType,
      设备厂商: item.manufacturer,
      设备状态: item.deviceStatus,
      部门编号: item.depNo,
      部门名称: item.depName,
      采集站编号: item.stationNo,
      采集站名称: item.stationName,
      国际编号: item.interNo,
      用户编号: item.userNo,
      用户名称: item.userName,
      备注: item.remark,
      创建时间: item.createTime
    })
  })
  return arr
}
const exportToExcel = () => {
  // 创建一个工作簿
  const workbook = XLSX.utils.book_new()
  // 创建一个工作表
  const worksheet = XLSX.utils.json_to_sheet(handleData())

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')
  // 生成Excel文件
  XLSX.writeFile(workbook, '设备列表.xlsx')
}
const successFile = (e) => {
  console.log('successFile-------', e)
  if (e.code == 0) {
    ElMessage.success('导入成功')
    showExport.value = false
    getList()
  } else {
    ElMessage.error(e.msg || '导入失败')
  }
}
const downExcel = async () => {
  const res = await downloadDeviceTemplateApi()
  if (res) {
    const excelFile = new Blob([res.data], {
      type: 'application/vnd.ms-excel'
    })

    // const url = URL.createObjectURL(excelFile)
    const url = window.URL.createObjectURL(excelFile)
    const a: HTMLAnchorElement = document.createElement('a')
    // 设置<a>元素的属性
    a.href = url
    a.download = '设备模板.xlsx'
    // 将<a>元素添加到文档中
    document.body.appendChild(a)
    // 触发点击事件
    a.click()
    URL.revokeObjectURL(a.href)
    // 移除<a>元素
    document.body.removeChild(a)
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @reset="setSearchParams" @search="setSearchParams" />
    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction" v-if="haspermiss.includes('新增')">{{
        t('exampleDemo.add')
      }}</BaseButton>
      <BaseButton
        :loading="delLoading"
        type="danger"
        @click="delData('')"
        v-if="haspermiss.includes('删除')"
      >
        {{ t('exampleDemo.del') }}
      </BaseButton>
      <BaseButton type="primary" @click="showExport = true" v-if="haspermiss.includes('导入')">{{
        t('exampleDemo.import')
      }}</BaseButton>
      <BaseButton type="primary" @click="exportToExcel" v-if="haspermiss.includes('导出')">{{
        t('exampleDemo.exprot')
      }}</BaseButton>
      <BaseButton type="primary" @click="downExcel">下载模板</BaseButton>
    </div>
    <Table
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :reserveIndex="true"
      :columns="allSchemas.tableColumns"
      node-key="guid"
      :data="dataList"
      :showAction="true"
      :loading="loading"
      :pagination="{
        total
      }"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :current-row="currentRow"
      :form-schema="allSchemas.formSchema"
    />
    <Detail v-else :current-row="currentRow" :detail-schema="allSchemas.detailSchema" />

    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
  <Dialog v-model="showExport" title="导入模板">
    <div class="uploaddiv">
      <!--  :action="uploadUrl" -->
      <ElUpload
        accept=".xlsx, .xls"
        drag
        action="/api/Device/ExportDevices"
        :headers="headers"
        :on-success="successFile"
      >
        <el-icon class="el-icon--upload"><Plus /></el-icon>
        <div class="el-upload__text">点击或拖拽文件到此处上传</div>
        <div class="el-upload__text">支持.xlsx, .xls</div>
      </ElUpload>
    </div>
    <template #footer>
      <BaseButton @click="showExport = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
